/*
*IWA project - result.js
*Maximilian Einoeder
*Mark Mensing
*/

//Stuff to init the map display
var directionsDisplay;
var directionsDisplayRail;
var directionsService = new google.maps.DirectionsService();
var directionsServiceRail = new google.maps.DirectionsService();
var map;
var mapRail;

$(document).ready(function() {    
    //To fold the content under a content header
    $('.contentHeader').click(function() {
        $(this).parent().parent().next().toggle('fold');
    });
    
    //Create a loading image
    var $loadingDialog = $('<div><img src="../img/loader.gif" style="margin:auto;display:block;" /></div>')
        .dialog({
            autoOpen: false,
            modal: true,
            title:  'Please wait',
            closeOnEscape: false,
            open: function(event, ui) {$(".ui-dialog-titlebar-close", $(this).parent()).hide();}
        });
    
    //Add radio button event for the car route shoing
    $('.radioRoad').live('click', function() {
        
        //Get lat and lng
        var arr = $(this).val().split('+');
        
        //Get the start and end point
        var start = $('#inputFrom').val();
        var end = $('#inputTo').val()
        
        //Create a request to show the new route
        var request = {
            origin:start, 
            destination:end,
            waypoints: [
            {
                location: new google.maps.LatLng(arr[0], arr[1]),
                stopover:true
            }
            ],
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        
        //Request and show the new route
        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            }
        });
    });
    
    //Open a dialog when a link with the dialogLink class is clicked
    $('.dialogLink').live('click', function() {
        //Create a dialog
        var $dialog = $('<div></div>')
        .dialog({
            autoOpen: false,
            width: 1000,
            position: 'top',
            title:  $(this).html()
        });
        
        //Make a ajax request to details.php to get details about the POI
        //details.php?s=Stadion%20Galgenwaard
        var data = {};
        //Cheating a bit here ;)
        if($(this).html() == 'Dierenpark Amersfoort') {
            data['s'] = 'DierenPark Amersfoort';
        }
        else {
            data['s'] = $(this).html();
        }
        //Get lat and long
        //Get lat and lng
        var coords = $(this).attr('href').split('+');
        
        data['lat'] = coords[0];
        data['lng'] = coords[1];
        
        $.ajax({
            url: 'details.php',
            type: 'GET',
            data: data,
            success: function(msg) {
                $dialog.dialog('open');
                $dialog.html(msg);
            }
        });
        
        //        $dialog.dialog('open');
        //        $dialog.html('You just clicked ' + $(this).attr('href') + '. </br> If you want to add something use a php function that outputs some text');
        
        // prevent the default action
        return false;
    });
    
    //If a train radio button is clicked
    $('.radioTrain').live('click', function() {
        var arr = $(this).val().split('+');
        var infoText = 'Please leave the train in <b>'+arr[5]+'</b> and make your own way to <b>'+arr[4]+'</b>:';
document.getElementById("infotext").innerHTML = infoText;
        var startTrain = new google.maps.LatLng(arr[2], arr[3]);
        var endTrain = new google.maps.LatLng(arr[0], arr[1]);
                
        //Create a request to show the new route
        var requestTrain = {
            origin:startTrain, 
            destination:endTrain,
            travelMode: google.maps.DirectionsTravelMode.WALKING
        };
        
        //Request and show the new route
        directionsService.route(requestTrain, function(responseTrain, statusTrain) {
            if (statusTrain == google.maps.DirectionsStatus.OK) {
                directionsDisplayRail.setDirections(responseTrain);
            }
        });
    });

    
    //When a checkbox with the class selectFeature is clicked
    $('.selectFeature').click(function() {
        //Show loader
        $loadingDialog.dialog('open');
        
        //Create the first request to filter the train POI's again
        
        //Set the function to do
        var data = {};
        data['function'] = 'filter';
        
        //Add the information like date and time from index.html
        data['From'] = $('#inputFrom').val();
        data['To'] = $('#inputTo').val();
        data['Date'] = $('#inputDate').val();
        data['Time'] = $('#inputTime').val();
        
        var counter = 0;        
        var filters = new Array();
        
        $.each($('.selectFeature'),function(){
            if($(this).attr('checked')) {
                filters[counter] = $(this).val();
                counter++;
            }
        });
        
        if(filters.length > 0) {
            data ['filters'] = filters;
        
            $.ajax({
                url: 'ajax.php',
                type: 'POST',
                data: data,
                dataType: 'json',
                success: function(msg) {
                    
                    if(msg == 'error') {
                        var $errorDialog = $('<div>Something seems to have gone wrong. Please try again</div>')
                        .dialog({
                            autoOpen: false,
                            title:  'Error'
                        });
                        
                        $errorDialog.dialog('open');
                    }
                    else {
                        //Start with the car POI
                    //Remove the table rows, except the first one
                    $('#resultCar').find("tr:gt(0)").remove();
                
                    for(sub in msg[0]) {
                        //Build html table row
                        var inner = '<tr>';
                    
                        if(!sub) {
                            inner += '<td width="20"><input type="radio" name="road" class="radioRoad" value="'+msg[0][sub][3]+'+'+msg[0][sub][4]+'" checked/></td>';
//                            value="latitude: <? echo $r['lat']; ?>, longitude: <? echo $r['lng'];?>"
                        }
                        else {
                            inner += '<td width="20"><input type="radio" name="road" class="radioRoad" value="'+msg[0][sub][3]+'+'+msg[0][sub][4]+'"/></td>';
                        }                    
                        inner += '<td><a class="dialogLink" href="'+msg[0][sub][3]+'+'+msg[0][sub][4]+'">'+ msg[0][sub][0] +'</a></td>';
                        inner += '<td>' + msg[0][sub][1] + ' km</td>';
                        inner += '<td>' + msg[0][sub][2] + '</td>';
                        //inner += '<td><a href="' + escape(msg[0][sub][0]) + '" class="dialogLink">open</td>';
                        inner += '</tr>';
                    
                        //Add table row
                        $('#resultCar > tbody:last').append(inner);
                    }
                
                    //Remove the table rows, except the first one
                    $('#resultRail').find("tr:gt(0)").remove();
                
                    //Add the new rows
                
                    for(subTrain in msg[1]) {
                        //Build html table row
                        var innerTrain = '<tr>';
                    
                        if(!subTrain) {
                            innerTrain += '<td width="20"><input type="radio" name="radioTrain" class="radioTrain" value="'+msg[1][subTrain][4]+'+'+msg[1][subTrain][5]+ '+'+ msg[1][subTrain][6]+'+' + msg[1][subTrain][7] + '+' + msg[1][subTrain][0] + '+' + msg[1][subTrain][8] +'" checked/></td>';
                        }
                        else {
                            innerTrain += '<td width="20"><input type="radio" name="radioTrain" class="radioTrain" value="'+msg[1][subTrain][4]+'+'+msg[1][subTrain][5]+ '+'+ msg[1][subTrain][6]+'+' + msg[1][subTrain][7] + '+' + msg[1][subTrain][0] + '+' + msg[1][subTrain][8] +'"/></td>';
                        }                    
                        innerTrain += '<td><a class="dialogLink" href="'+msg[1][subTrain][4]+'+'+msg[1][subTrain][5]+'">'+ msg[1][subTrain][0] +'</a></td>';
                        innerTrain += '<td>' + msg[1][subTrain][1] + ' km</td>';
                       // innerTrain += '<td>' + msg[1][subTrain][2] + '</td>';
                        innerTrain += '<td>' + msg[1][subTrain][3] + '</td>';
                        //innerTrain += '<td><a href="' + escape(msg[1][subTrain][0]) + '" class="dialogLink">open</td>';
                        innerTrain += '</tr>';
                        //Add table row
                        $('#resultRail > tbody:last').append(innerTrain);
                    }
                    
                    //Hide the loader
                    $loadingDialog.dialog('close');
                    }
                }
            });
        }
        else {
            //Just empty the tables
            $('#resultCar').find("tr:gt(0)").remove();
            $('#resultRail').find("tr:gt(0)").remove();
            
            //Hide the loader
            $loadingDialog.dialog('close');
        }
    });
});


//init the map
function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    directionsDisplayRail = new google.maps.DirectionsRenderer();
    //Center the map on the Netherlands
    var nl = new google.maps.LatLng(51.916667, 5.566667);
    var myOptions = {
      zoom:7,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: nl
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);
    
    mapRail = new google.maps.Map(document.getElementById("map_canvas_train"), myOptions);
    directionsDisplayRail.setMap(mapRail);
}
 
